package com.ayi.servlet.base; /**
 * @author Ayingzz
 * @create 2021/11/29 13:35
 */

import com.ayi.bean.User;
import com.ayi.dao.cartdao.AddCart;
import com.ayi.dao.userdao.AddUser;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "RegisterServlet", value = "/RegisterServlet")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String username = request.getParameter("usernameR");
        String password = request.getParameter("passwordR");
        String password0 = request.getParameter("passwordR0");
        boolean isAdmin = "yes".equals(request.getParameter("isAdmin"));
        if (!username.equals("") && password.equals(password0)) {
            User user = new User(username, password, isAdmin, false);
            if (new AddUser().addUser(user)) {
                new AddCart().addCart(user.getUsername());
                response.sendRedirect("login.jsp");
            } else {
                response.getWriter().print("用户名已存在，请重新输入注册信息...3秒后返回注册页面");
                response.setHeader("refresh", "3;url=" + request.getContextPath() + "/register.jsp");
                return;
            }
        } else {
            response.getWriter().print("用户名非法，或两次密码不一致，请重新输入注册信息...3秒后返回注册页面");
            response.setHeader("refresh", "3;url=" + request.getContextPath() + "/register.jsp");
            return;
        }
    }
}
